package com.cupk.controller;

import com.cupk.pojo.Match;
import com.cupk.pojo.Result;
import com.cupk.pojo.Stage;
import com.cupk.service.StageService;
import com.cupk.service.impl.MatchServiceImpl;
import com.cupk.utils.ThreadLocalUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/stage")
public class StageController {
    @Autowired
    private StageService stageService;

    @GetMapping("/list")
    public Result<List<Stage>> getStageList(@RequestParam Integer matchId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        //System.out.println(userId);
        if (!stageService.judgeLegal(matchId, userId, role)) {
            return Result.error("比赛阶段请求非法！");
        }
        List<Stage> ls = stageService.getListByMatchId(matchId);
        return Result.success(ls);
    }

    @PostMapping("/add")
    public Result addStage(@RequestBody Stage stage) {
        if (!stageService.judgeLegal(stage)) {
            return Result.error("比赛阶段请求非法！");
        }
        Integer matchId = stage.getMatchId();
        Integer period = stageService.findMaxPeriod(matchId) + 1;
        stage.setPeriodId(period);
        stageService.addStage(stage);
        return Result.success();
    }

    @PutMapping("/update")
    public Result updateStage(@RequestBody Stage stage) {
        if (!stageService.judgeLegal(stage)) {
            return Result.error("比赛阶段请求非法！");
        }
        Stage res = stageService.getStageById(stage.getId());
        if (res == null) {
            return Result.error("阶段ID请求非法！");
        }
        stageService.updateStage(stage);
        return Result.success();
    }

    @DeleteMapping("/del")
    public Result deleteStage(@RequestParam Integer id) {
        Stage res = stageService.getStageById(id);
        if (res == null) {
            return Result.error("阶段ID请求非法！");
        }
        stageService.deleteStage(id);
        return Result.success();
    }

    @GetMapping("/getNowList")
    public Result<List<Stage>> getNowStage(@RequestParam Integer matchId) {
        List<Stage> ls = stageService.getEffectListByMatchId(matchId);
        if (ls.size() == 0) {
            return Result.error("当前比赛所有环节均未开始或已结束");
        }
        return Result.success(ls);
    }
}
